import cloud from './shareCloud';

// 获取数据
// gather: 集合名(string),  query: 查询参数(object),  boolean: 是否显示加载框(boolean)
export const getCloudData = (gather, query, boolean = true, limit = 20, skip = 0) => {
  return new Promise(async (resolve, reject) => {
    const c1 = cloud();
    await c1.init();
    if (boolean) {
      wx.showLoading({
        title: 'Loading...',
      })
    }
    wx.showNavigationBarLoading();
    c1.database()
      .collection(gather)
      .where(query)
      .limit(limit)
      .skip(skip)
      .get({
        success: (res) => {
          resolve(res.data);
        },
        fail: (err) => {
          wx.showModal({
            title: '错误提示',
            content: err,
            showCancel: false,
            complete: (res) => {
              if (res.confirm) { }
            }
          })
        },
        complete: () => {
          wx.hideLoading();
          wx.stopPullDownRefresh();
          wx.hideNavigationBarLoading();
        }
      });
  })
}

// 更新数据
// gather: 集合名(string), query: 查询参数(object), data: 更新数据(object), callback: 回调函数(function)
export const updateCloudData = (gather, query, boolean = true, data, callback) => {
  return new Promise(async (resolve, reject) => {
    const c1 = cloud();
    await c1.init();
    if (boolean) {
      wx.showLoading({
        title: 'Loading...',
      })
    }
    wx.showNavigationBarLoading();
    c1.database()
      .collection(gather)
      .where(query)
      .update({
        data,
        success: (res) => {
          wx.showToast({
            title: "更新成功",
            icon: "success",
          });
          callback();
        },
        fail: (err) => {
          wx.showToast({
            title: "更新失败",
            icon: "success",
          });
        },
        complete: () => {
          wx.hideLoading();
          wx.stopPullDownRefresh();
          wx.hideNavigationBarLoading();
        }
      });
  })
}


// 删除云数据库文件
export const delCloudFile = (fileId) => {
  wx.cloud.deleteFile({
    fileList: [fileId],
    success(res) {
      console.log(res, '删除文件')
    },
    fail(err) {
      console.log(err)
    }
  });
}

// module.exports = {
//   getCloudData,
//   delCloudFile
// }